package com.lanswon.qzsmk.util.inventoryUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lanswon.qzsmk.dao.CardTaskMapper;
import com.lanswon.qzsmk.model.CardTask;

import ch.qos.logback.classic.Logger;

@Component
public class CheckFileUtil {
	private static Logger logger = (Logger) LoggerFactory.getLogger(CheckFileUtil.class);
	
	private final static String[] cardCodeArr = {"1000","1010","1020","1030","1040","1050","1100","1200","1350","1450","1550"};
	private final static String QJMKTITLE = "记名卡制卡文件|Q.非接触芯片号|Q.非接卡PIN|Q.市民卡卡面号|Q.发卡日期|Q.卡片序列号|Q.银行卡号|Q.银行卡有效期|Q.制卡结果|Q.制卡失败原因|证件种类|证件号码|姓名|性别|民族"
											+"|出生日期|户籍地址|手机号|家庭地址|邮政编码|家长手机号|所在学校|所在班级|3F00.0005.发卡方标识|3F00.0005.区划代码|3F00.0005.工程项目代码|3F00.0005.卡主类型"
											+"|3F00.0005.卡子类型|3F00.0005.市民卡卡号|3F00.0005.市民卡校验码|3F01.0015.发卡方标识|3F01.0015.行政区划码|3F01.0015.工程项目代码|3F01.0015.户籍编码"
											+"|3F01.0015.应用类型标识|3F01.0015.应用版本|3F01.0015.应用序列号|3F01.0015.卡类型|3F01.0015.押金|3F02.0015.发卡方标识|3F02.0015.区划码|3F02.0015.项目代码预留"
											+"|3F02.0015.应用类型标识|3F02.0015.应用版本|3F02.0015.应用序列号|3F02.0015.卡类型|3F02.0015.押金|3F10.0015.应用状态标识|3F10.0015.初始化版本|3F10.0015.应用序列号"
											+"|3F10.0015.初始化启动日期|9A00.0015.行业大类代码|9A00.0015.单位编号|9A00.0015.应用类型标识|9A00.0015.应用版本|9A00.0015.应用序列号|9A00.0015.卡类型|9A00.0016.单位员工编号"
											+"|9A00.0016.补充企业系统唯一码";
	private final static String QBJMTITLE = "RBJM_FILENAME|CARD_TASK_NO|TOTAL|SUCCESS|FAIL|FAIL_CARDS";
	
	@Autowired
	CardTaskMapper ctm;
	
	/**
	 * 功能：检查文件名称的正确性
	 * @param subFileName
	 * @return
	 */
	public boolean checkFileName(String subFileName) {
		logger.info("checkFile########start()");
		boolean nameFlag = false;
		//判断文件名的长度
		if(subFileName.length()!=18){
			return nameFlag;
		}
		
		//截取头四个字符串，进行判断
		String fileTitle =  subFileName.substring(0, 4);
		if(!"QJMK".equals(fileTitle)&&!"QBJM".equals(fileTitle)){
			return nameFlag;
		}
		//判断卡类型
		String cardCode = subFileName.substring(4, 8);
		logger.debug("cardCode==>"+cardCode);
		for(int i=0;i<cardCodeArr.length;i++){
			if(cardCodeArr[i].equals(cardCode)){
				break;
			}
			if(i==(cardCodeArr.length-1)){
				return nameFlag;
			}
		}
		//截取中间四个字符串，进行判断
		String fileYear = "20"+subFileName.substring(8, 10);
		String fileMonth = subFileName.substring(10, 12);
		logger.debug("fileYear===>"+fileYear);
		logger.debug("fileMonth===>"+fileMonth);
		String fileDay = subFileName.substring(12, 14);
		logger.debug("fileDay===>"+fileDay);
		//如果月是1，3，5，7，8，10，12
		List<String> bigMonthList = new ArrayList<String>(Arrays.asList("01","03","05","07","08","10","12"));
		List<String> smallMonthList = new ArrayList<String>(Arrays.asList("04","06","09","11"));
		if(smallMonthList.contains(fileMonth)){
			logger.debug("月份是小月");
			if(Integer.parseInt(fileDay)>30){
				return nameFlag;
			}
		}else if("02".equals(fileMonth)){
			//判断是否是闰年
			int year = Integer.parseInt(fileYear);
			if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0){
				if(Integer.parseInt(fileDay)>29){
					return nameFlag;
				}
			}else{
				if(Integer.parseInt(fileDay)>28){
					return nameFlag;
				}
			}
		}else if(bigMonthList.contains(fileMonth)){
			logger.debug("月份是大月");
			if(Integer.parseInt(fileDay)>31){
				return nameFlag;
			}
		}else{
			return nameFlag;
		}
		logger.info("checkFile########end()");
		return true;
	}
	
	/**
	 * 查询制卡文件是否导入过了
	 * @param subFileName
	 * @return
	 */
	public boolean checkFileStatus(String subFileName) {
		logger.info("checkFileStatus########start()");
		//首先判断数据库中的制卡文件批次是否已有导入过
		
		String batchMakeNo = subFileName.substring(8);
		logger.debug("batchMakeNo==>"+batchMakeNo);
		List<CardTask> taskStatusList = ctm.queryTaskStatusMakerNo(batchMakeNo);
		if(taskStatusList.size()<1){
			return false;
		}
		for(CardTask taskList:taskStatusList){
			//如果是5：已制卡或者6：部分制卡，返回false
			if("5".equals(taskList.getTaskStatus())){
				return false;
			}
		}		
		logger.info("checkFileStatus########end()");
		return true;
	}
	
	/**
	 * 查询制卡文件是否导入过了
	 * @param subFileName
	 * @return
	 * @throws IOException 
	 */
	public boolean checkFileFormat(File file) throws IOException {
		logger.info("checkFileFormat########start()");
		boolean flag = true;
		FileInputStream fis = new FileInputStream(file);
		InputStreamReader isr = new InputStreamReader(fis,"gbk");
		BufferedReader reader = new BufferedReader(isr);
		String line = null;
		List<String> lineList = new ArrayList<String>();
		while ((line = reader.readLine()) != null) {
			lineList.add(line);
        }

		//判断抬头是否正确 
		String title = lineList.get(0);
		if(!QJMKTITLE.equals(title) && !QBJMTITLE.equals(title)){
			flag = false;
		}
		int titleArraySize = title.split("\\|").length;
		//检查每一行的内容完整性，不检查格式
		if(lineList.size()>1){
			for(int i=1;i<lineList.size();i++){
				int arraySize = lineList.get(i).split("\\|", -1).length;
				if("".equals(lineList.get(i))||lineList.get(i)==null){
					flag = false;
				}
				if(arraySize!=titleArraySize){
					flag = false;
				}
			}
		}else{
			flag = false;
		}
		if(!flag){
			if(reader!=null){
				reader.close();
				file.delete();
			}
		}
		
		if(reader!=null){
			reader.close();
		}
		logger.info("checkFileFormat########end()");
		return flag;
	}
}
